import { Teacher } from '../models/Teacher.js';
import { Class } from '../models/Class.js';
import { College } from '../models/College.js';
import { Student } from '../models/Student.js';

console.log('=== 加载 TeacherController ===');

// 初始化模型
const teacherModel = new Teacher();
const classModel = new Class();
const collegeModel = new College();
const studentModel = new Student();

console.log('模型初始化完成');

export class TeacherController {
  constructor() {
    console.log('TeacherController 构造函数被调用');
  }

  // 获取老师表单选项数据
  async getFormOptions(req, res) {
    try {
      console.log('获取老师表单选项数据');

      const colleges = collegeModel.findAll();
      const classes = classModel.findAll();

      const departments = [...new Set(colleges.map(college => college.name))];
      const titles = ['教授', '副教授', '讲师', '助教'];
      const majors = ['计算机科学与技术', '软件工程', '人工智能', '数据科学', '网络工程'];

      res.json({
        success: true,
        data: {
          departments,
          titles,
          majors,
          classes: classes.map(cls => cls.className)
        }
      });
    } catch (error) {
      console.error('获取老师表单选项失败:', error);
      res.status(500).json({
        success: false,
        error: '获取选项数据失败'
      });
    }
  }

  // 获取老师列表
  async getTeachers(req, res) {
    try {
      console.log('获取老师列表，查询参数:', req.query);

      const teachers = teacherModel.findAll();

      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;

      // 应用搜索过滤
      let filteredTeachers = [...teachers];

      // 关键词搜索
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredTeachers = filteredTeachers.filter(teacher => {
          const name = teacher.name || '';
          const teacherId = teacher.teacherId || '';
          const department = teacher.department || '';
          const major = teacher.major || '';
          const course = teacher.course || '';

          return name.toLowerCase().includes(keyword) ||
            teacherId.toLowerCase().includes(keyword) ||
            department.toLowerCase().includes(keyword) ||
            major.toLowerCase().includes(keyword) ||
            course.toLowerCase().includes(keyword);
        });
      }

      // 字段精确搜索
      const searchFields = ['name', 'teacherId', 'department', 'title', 'major', 'status'];
      searchFields.forEach(field => {
        if (req.query[field] && req.query[field].trim()) {
          const searchValue = req.query[field].toLowerCase();
          filteredTeachers = filteredTeachers.filter(teacher => {
            const fieldValue = teacher[field];
            return fieldValue && fieldValue.toString().toLowerCase().includes(searchValue);
          });
        }
      });

      // 分页
      const paginatedTeachers = filteredTeachers.slice(startIndex, endIndex);

      // 关联班级数据
      const classes = classModel.findAll();
      const teachersWithClasses = paginatedTeachers.map(teacher => {
        const teacherClasses = classes.filter(cls => cls.lecturer === teacher.name);
        return {
          ...teacher,
          classCount: teacherClasses.length,
          classes: teacherClasses
        };
      });

      // 构建响应
      const response = {
        success: true,
        data: teachersWithClasses,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: filteredTeachers.length,
          totalPages: Math.ceil(filteredTeachers.length / pageSize)
        }
      };

      console.log('返回老师数据:', {
        dataCount: teachersWithClasses.length,
        total: filteredTeachers.length
      });

      res.json(response);
    } catch (error) {
      console.error('获取老师列表时出错:', error);
      res.status(500).json({
        success: false,
        error: '服务器内部错误',
        message: error.message
      });
    }
  }

  // 获取老师详情
  async getTeacherDetail(req, res) {
    try {
      const { id } = req.params;
      console.log('获取老师详情:', id);

      const teacher = teacherModel.findById(id);
      if (!teacher) {
        return res.status(404).json({
          success: false,
          error: '老师不存在'
        });
      }

      // 关联班级数据和学生信息
      const classes = classModel.findAll();
      const students = studentModel.findAll();
      const teacherClasses = classes.filter(cls => cls.lecturer === teacher.name);
      
      // 为每个班级添加学生信息
      const classesWithStudents = teacherClasses.map(cls => {
        const classStudents = students.filter(student => 
          student.className === cls.className
        );
        return {
          ...cls,
          studentCount: classStudents.length,
          students: classStudents
        };
      });
      
      // 区分现在的班级和带过的班级（目前所有班级都作为现在的班级）
      // 可以根据需要添加历史班级的判断逻辑
      const currentClasses = classesWithStudents;
      const pastClasses = []; // 可以根据需求添加历史班级的逻辑
      

      const teacherDetail = {
        ...teacher,
        classes: classesWithStudents,
        currentClasses: currentClasses,
        pastClasses: pastClasses,
        classCount: teacherClasses.length,
        currentClassCount: currentClasses.length,
        pastClassCount: pastClasses.length
      };

      res.json({
        success: true,
        data: teacherDetail
      });
    } catch (error) {
      console.error('获取老师详情失败:', error);
      res.status(500).json({
        success: false,
        error: '获取失败'
      });
    }
  }

  // 获取老师统计信息
  async getTeacherStats(req, res) {
    try {
      const teachers = teacherModel.findAll();
      const classes = classModel.findAll();
      const colleges = collegeModel.findAll();

      const totalTeachers = teachers.length;
      const activeTeachers = teachers.filter(t => t.status === 'active').length;

      // 按部门统计
      const departmentStats = colleges.map(college => {
        const deptTeachers = teachers.filter(t => t.department === college.name);
        const deptClasses = classes.filter(cls => cls.department === college.name);

        return {
          department: college.name,
          teacherCount: deptTeachers.length,
          classCount: deptClasses.length,
          studentCount: deptClasses.reduce((sum, cls) => sum + (cls.studentCount || 0), 0)
        };
      });

      // 按职称统计
      const titleStats = teachers.reduce((acc, teacher) => {
        const title = teacher.title || '未设置';
        if (!acc[title]) {
          acc[title] = 0;
        }
        acc[title]++;
        return acc;
      }, {});

      res.json({
        success: true,
        data: {
          totalTeachers,
          activeTeachers,
          inactiveTeachers: totalTeachers - activeTeachers,
          departmentStats,
          titleStats,
          averageClassesPerTeacher: totalTeachers > 0 ? (classes.length / totalTeachers).toFixed(1) : 0
        }
      });
    } catch (error) {
      console.error('获取老师统计失败:', error);
      res.status(500).json({
        success: false,
        error: '获取失败'
      });
    }
  }

  // 创建老师
  async createTeacher(req, res) {
    try {
      const {
        name,
        gender,
        birthDate,
        idCard,
        phone,
        email,
        department,
        title,
        major,
        course,
        status
      } = req.body;

      console.log('创建老师:', { name });

      if (!name) {
        return res.status(400).json({
          success: false,
          error: '姓名为必填字段'
        });
      }

      const teachers = teacherModel.findAll();

      // 检查身份证号是否已存在
      if (idCard && teachers.find(t => t.idCard === idCard)) {
        return res.status(400).json({
          success: false,
          error: '身份证号已存在'
        });
      }

      const newTeacher = {
        name,
        gender: gender || '',
        birthDate: birthDate || '',
        idCard: idCard || '',
        phone: phone || '',
        email: email || '',
        department: department || '',
        title: title || '',
        major: major || '',
        course: course || '',
        status: status || 'active',
        hireDate: new Date().toISOString().split('T')[0]
      };

      const createdTeacher = teacherModel.create(newTeacher);

      if (createdTeacher) {
        console.log('创建老师成功:', createdTeacher);
        res.status(201).json({
          success: true,
          data: createdTeacher
        });
      } else {
        res.status(500).json({
          success: false,
          error: '保存失败'
        });
      }
    } catch (error) {
      console.error('创建老师失败:', error);
      res.status(500).json({
        success: false,
        error: '创建失败'
      });
    }
  }

  // 更新老师
  async updateTeacher(req, res) {
    try {
      const { id } = req.params;
      const {
        name,
        gender,
        birthDate,
        idCard,
        phone,
        email,
        department,
        title,
        major,
        course,
        status
      } = req.body;

      console.log('更新老师:', id, { name });

      const teachers = teacherModel.findAll();

      // 检查身份证号是否被其他老师使用
      if (idCard && teachers.find(t => t.idCard === idCard && t.id !== parseInt(id))) {
        return res.status(400).json({
          success: false,
          error: '身份证号已被其他老师使用'
        });
      }

      const updatedTeacher = teacherModel.update(id, {
        name,
        gender: gender || '',
        birthDate: birthDate || '',
        idCard: idCard || '',
        phone: phone || '',
        email: email || '',
        department: department || '',
        title: title || '',
        major: major || '',
        course: course || '',
        status: status || 'active'
      });

      if (updatedTeacher) {
        console.log('更新老师成功:', updatedTeacher);
        res.json({
          success: true,
          data: updatedTeacher
        });
      } else {
        res.status(404).json({
          success: false,
          error: '老师不存在'
        });
      }
    } catch (error) {
      console.error('更新老师失败:', error);
      res.status(500).json({
        success: false,
        error: '更新失败'
      });
    }
  }

  // 删除老师
  async deleteTeacher(req, res) {
    try {
      const { id } = req.params;
      console.log('删除老师:', id);

      const teachers = teacherModel.findAll();
      const classes = classModel.findAll();

      // 检查是否有班级关联此老师
      const teacher = teachers.find(t => t.id === parseInt(id));
      if (teacher) {
        const relatedClasses = classes.filter(cls => cls.lecturer === teacher.name);
        if (relatedClasses.length > 0) {
          return res.status(400).json({
            success: false,
            error: `无法删除，该老师还负责 ${relatedClasses.length} 个班级`
          });
        }
      }

      const success = teacherModel.delete(id);

      if (success) {
        console.log('删除老师成功');
        res.json({
          success: true,
          message: '删除成功'
        });
      } else {
        res.status(404).json({
          success: false,
          error: '老师不存在'
        });
      }
    } catch (error) {
      console.error('删除老师失败:', error);
      res.status(500).json({
        success: false,
        error: '删除失败'
      });
    }
  }
}